package com.zdw.gateway.config.satoken;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.json.JSONUtil;
import com.zdw.gateway.entity.PermissionEntity;
import com.zdw.gateway.entity.RoleEntity;
import com.zdw.gateway.service.PermissionService;
import com.zdw.gateway.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 卓德文
 * @title: 获取角色和权限
 * @date 2022/12/22
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleService roleService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 使用根据loginId动态查询对应权限
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        //1.查询权限列表
        List<PermissionEntity> permissions = permissionService.selectPermissionsByUserId(Integer.parseInt(loginId.toString()));

        //2.用户权限
        List<String> permissionList = new ArrayList<>();
        permissions.forEach(x -> permissionList.add(x.getCode()));
        log.info("当前用户:" + loginId + ",权限列表:" + JSONUtil.toJsonStr(permissionList));

        //3.将权限信息存入redis缓存
        stringRedisTemplate.opsForValue().set("user:permission:" + loginId, JSONUtil.toJsonStr(permissionList), 3600, TimeUnit.SECONDS);

        //4.查询角色列表(网关只有鉴权,只会查询权限,不会查询角色,只能在查询权限的时候顺便查询角色,并存入Redis缓存)
        List<RoleEntity> roles = roleService.selectRolesByUserId(Integer.parseInt(loginId.toString()));

        //5.用户角色
        List<String> roleList = new ArrayList<>();
        roles.forEach(x -> roleList.add(x.getCode()));
        log.info("当前用户:" + loginId + ",角色列表:" + JSONUtil.toJsonStr(roleList));

        //6.将角色信息存入Redis缓存
        stringRedisTemplate.opsForValue().set("user:role:" + loginId, JSONUtil.toJsonStr(roleList), 3600, TimeUnit.SECONDS);

        return permissionList;
    }

    /**
     * 使用根据loginId动态查询对应角色(*)
     * (网关只有鉴权,只会查询权限,不会查询角色,坑爹啊)
     * (只能在查询权限的时候顺便查询角色,并存入Redis缓存,然后在各个业务模块取出)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        //1.查询角色列表
        List<RoleEntity> roles = roleService.selectRolesByUserId(Integer.parseInt(loginId.toString()));

        //2.用户角色
        List<String> roleList = new ArrayList<>();
        roles.forEach(x -> roleList.add(x.getCode()));
        log.info("当前用户:" + loginId + ",角色列表:" + JSONUtil.toJsonStr(roleList));

        //3.将角色信息存入Redis缓存
        stringRedisTemplate.opsForValue().set("user:role:" + loginId, JSONUtil.toJsonStr(roleList), 3600, TimeUnit.SECONDS);

        return roleList;
    }

}